var utils = require("../utils.js");
var read_article = require("./read_article.js");

var treasure_chest_storage = storages.create("treasure_chest");

function get_treasure_chest_times() {
  return treasure_chest_storage.get("times") || 0;
}
function set_treasure_chest_times(times) {
  treasure_chest_storage.put("times", times);
}
function get_treasure_chest_ad_times() {
  return treasure_chest_storage.get("ad_times") || 0;
}
function set_treasure_chest_ad_times(ad_times) {
  treasure_chest_storage.put("ad_times", ad_times);
}
var treasure_chest_point_map = {
  任务: [278, 1534, 441, 1618],
};
var treasure_chest = {
  init() {
    sleep(5 * 1000);
    if (utils.exists_text("百度") && utils.exists_text("我的")) {
      utils.click_point.apply(null, treasure_chest_point_map["任务"]);
      utils.click_text("开心收下");
      var adUIText = utils.click_text_starts_with("看广告再得");
      if (adUIText) {
        this.execute(adUIText.text());
        return;
      }
      if (utils.click_text("开宝箱得金币")) {
        var times = get_treasure_chest_times();
        set_treasure_chest_times(times + 1);
        console.log("treasure_chest init:", "宝箱已开", times + 1, "次");
        sleep(2 * 1000);
        var uiText = utils.click_text_starts_with("观看视频再得");
        if (uiText) {
          this.execute(uiText.text());
        } else {
          console.log("treasure_chest init", "没找到【观看视频再得】");
          this.end();
        }
      } else {
        console.log("treasure_chest init", "没找到【开宝箱得金币】");
        this.end();
      }
    } else {
      console.log("treasure_chest init", "没找到【百度】【我的】");
      this.end();
    }
  },
  execute(content) {
    console.log(content);
    var gold = content.match(/(\d+)/g) || 0;
    console.log(gold);
    sleep(2 * 1000);
    console.log("treasure_chest execute:", "2s");
    sleep(random(35, 38) * 1000);
    console.log("treasure_chest execute:", "35s");

    back();

    sleep(2 * 1000);
    this.after();
  },
  after() {
    var ad_times = get_treasure_chest_ad_times();
    set_treasure_chest_ad_times(ad_times + 1);
    console.log("treasure_chest after:", "视频已看", ad_times + 1, "次");
    var uiText = utils.click_text_starts_with("再看一个领取");
    if (uiText) {
      this.execute(uiText.text());
    } else {
      this.end();
    }
  },
  end() {
    sleep(2 * 1000);
    if (!utils.click_text_starts_with("立即收下")) {
      utils.click_text_starts_with("开心收下");
    }
    sleep(2 * 1000);
    if (utils.click_text_starts_with("看广告再得")) {
      this.init();
      return;
    }
    if (!utils.click_text("百度")) {
      console.log("treasure_chest end:", "没找到【百度】");
    }
    sleep(2 * 1000);
    if (!utils.click_text("视频")) {
      console.log("treasure_chest end:", "没找到【视频】");
    }
    console.log("treasure_chest end:");
    this.next();
  },
  next() {
    console.log("treasure_chest next:");
    read_article.init();
  },
};
module.exports = treasure_chest;
